package com.swehr.servlet;


import com.swehr.model.Personnel;
import com.swehr.model.ResultInfo;
import com.swehr.proxy.PersonnelServiceProxy;
import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author Rock Huang
 * @version 0.1
 */
public class PersonnelServlet extends HttpServlet {

    private static final Logger log = Logger.getLogger(PersonnelServlet.class);

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException, ServletException {
        ServletUtils.printRequestInfo(req);
        if (ServletUtils.toSignin(req, resp)) return;
        req.setAttribute("checked", "Personnel");
        ServletUtils.forward(req, resp);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws IOException, ServletException {
        ServletUtils.printRequestInfo(req);
        ObjectMapper mapper = new ObjectMapper();
        String json = req.getParameter("carrier");
        List<Personnel> psns = mapper.readValue(json, new TypeReference<List<Personnel>>(){});

        for (Personnel e: psns) {
            if (e.getId()==0) System.out.println("Created: \n ================");
            else if (e.getId()>0) System.out.println("Updated \n ===============");
            else if (e.getId() == -1) System.out.println("Delete \n ===============");
            else {System.out.println("unexpected data");}
            System.out.println(e.toString());
        }

        ResultInfo rs = new PersonnelServiceProxy().savePsn(psns);
        resp.getWriter().println(rs.toString());
    }

    protected void doPut(HttpServletRequest req, HttpServletResponse resp) {
        ServletUtils.printRequestInfo(req);
    }

    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) {
        ServletUtils.printRequestInfo(req);
    }
}
